<template>
  <div>
    <!-- 标题 -->
    <row-vet></row-vet>
    <!-- 标题 -->
    <div class="head">
      <van-icon name="shop-o" size="20" />购物车列表
    </div>
    <div class="MainBody">
      <!-- 购物车按钮 -->
      <van-row v-for="(item,index) in carList" :key="index">
        <van-swipe-cell>
          <van-col span="2">
            <van-checkbox
              class="checkbox"
              v-model="item.checked"
              checked-color="#D81E06"
              @change="chooseChange(item.goods_id, item)"
            ></van-checkbox>
          </van-col>
          <!-- 购物车列表 -->
          <van-col class="GoodsDetails" span="20">
            <van-card
              :price="item.goods_price"
              :desc="item.goods_name"
              :thumb="item.goods_small_logo"
            ></van-card>
            <!-- 商品数量按钮 -->
            <van-stepper v-model="item.num" min="1" @change="(value) => {NumChange(value,item)}" />
          </van-col>
          <!--滑动删除 -->
          <template slot="right">
            <van-button square type="danger" text="删除" @click="removeShop(index,item.goods_id)" />
          </template>
        </van-swipe-cell>
      </van-row>
      <row-vit></row-vit>
      <!-- 提交订单 -->
      <van-submit-bar
        :price="totalPrice"
        button-text="提交订单"
        safe-area-inset-bottom
        @submit="onSubmit"
      >
        <!-- 全选按钮 -->
        <van-checkbox
          label-position="right"
          v-model="AllChecked"
          checked-color="#D81E06"
          @click="checkAll"
        >全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>
<script>
import minfo from '../util/navigation'
import header from '../util/header'
// import { mapGetters } from 'vuex'
// import { log } from 'util'
export default {
  data() {
    return {
      value: 1,
      selectedData: [],
      AllChecked: false,
      checked: false,
      chooseArr: [],
      carList: [],
      // 获取本地数据，次数，去重
      getcarList: [],
      totalPrice: 0,
      arr: []
    }
  },
  components: {
    'row-vit': minfo,
    'row-vet': header
  },
  created() {
    // this.carList = JSON.parse(localStorage.getItem('goshop'))

    this.getcarList = JSON.parse(localStorage.getItem('goshop'))
    if (this.getcarList === null) {
      this.carList = []
    } else {
      const arr = Array.from(this.getcarList)
      // 数组去重
      let newobj = {}
      const list = arr.reduce((preVal, curVal) => {
        newobj[curVal.goods_id]
          ? ''
          : (newobj[curVal.goods_id] = preVal.push(curVal))
        return preVal
      }, [])
      // 获取每一项出现的次数
      let obj = new Object()
      for (let i = 0; i < this.getcarList.length; i++) {
        if (obj[this.getcarList[i].goods_id]) {
          obj[this.getcarList[i].goods_id]++
        } else {
          obj[this.getcarList[i].goods_id] = 1
        }
      }
      for (var k in obj) {
        console.log(`${k} 的次数是:${obj[k]}`)
        console.log(k)
        list.forEach(item => {
          if (item.goods_id == k) {
            item.num = obj[k]
          }
        })
      }
      console.log(list)
      this.carList = list
    }
    console.log(this.getcarList)
  },
  methods: {
    getTotalPrice(item) {
      let total = 0
      this.carList.forEach(item => {
        if (item.checked) {
          total += item.goods_price * item.num
        }
      })
      this.totalPrice = total * 100
    },
    chooseChange(id, item) {
      this.chooseArr = []
      this.carList.forEach(element => {
        if (element.checked === true) {
          this.chooseArr.push(element.goods_id)
        }
        if (this.chooseArr.length < this.carList.length) {
          this.AllChecked = false
        } else {
          this.AllChecked = true
        }
        this.getTotalPrice(item)
      })
    },
    NumChange(value, item) {
      console.log(item.num)
      this.getTotalPrice(item)
      // 动态改变购物车上面的infos值
      let allNum = 0
      this.carList.forEach(item => {
        allNum += item.num
      })
      
      window.localStorage.setItem('nane', allNum)
    },
    checkAll() {
      let list = this.carList
      if (this.AllChecked) {
        list.forEach(element => {
          element.checked = false
        })
        this.selectedData = []
      } else {
        list.forEach(element => {
          element.checked = true
          if (this.selectedData.indexOf(element.goods_id) < 0) {
            this.selectedData.push(element.goods_id)
          }
        })
      }
    },
    // 提交订单时把数据存储本地，并跳转页面
    onSubmit() {
      let newgoods = []
      this.carList.forEach(item => {
        if (item.checked) {
          newgoods.push(item)
        } else {
          return
        }
      })
      window.localStorage.setItem('newgood', JSON.stringify(newgoods))
      this.$router.push('/order')
    },
    // removeShop(index) {
    //   this.carList.splice(index, 1)
    //   this.getTotalPrice()
    // },
    removeShop(index, id) {
      this.carList.splice(index, 1)
      this.arr = JSON.parse(localStorage.getItem('goshop'))
      console.log(this.arr + '----')
      for (let i = 0; i < this.arr.length; i++) {
        if (this.arr[i].goods_id === id) {
          this.arr.splice(i, 1)
        }
      }
      window.localStorage.setItem('goshop', JSON.stringify(this.arr))
      this.getcarList = JSON.parse(localStorage.getItem('goshop'))
    }
  }
}
</script>
<style lang="less" scoped>
.head {
  margin: 1.5rem 0 0.2rem 0.2rem;
  font-size: 15px;
  .van-icon {
    vertical-align: text-bottom;
    margin-right: 3px;
  }
}
.MainBody {
  padding-bottom: 100px;
}
.van-row {
  width: 100%;
  background-color: #fafafa;

  .GoodsDetails {
    position: relative;
    .van-stepper {
      position: absolute;
      transform: translate(6.2rem, -0.93333rem);
    }
  }
}
.checkbox {
  margin-top: 1.2rem;
  margin-left: 0.26667rem;
}
.shopCarCheck {
  padding-top: 15px;
}
.van-submit-bar {
  bottom: 50px;
}
.van-button--square {
  height: 100px;
}
</style>